package Jdbc;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class SubjectDao {
    public int add(Subject subject){
        String sql="insert into s_subject (id,subjectname,classhour,gradeid) values (?,?,?,?)";
        return  DBUtil.executeUpdate(sql,subject.getId(),subject.getSubjectname(),subject.getClasshour(),subject.getGradeid());
    }
    public int update(Subject subject){
        String sql = "update from s_subject set subjectname=? where id=?";
        return DBUtil.executeUpdate(sql, subject.getSubjectname(), subject.getId());
    }
    public int delete(Subject subject){
        String sql="delect from s_subject where id=?";
        return  DBUtil.executeUpdate(sql,subject.getId());
    }
    public List<Subject> findid(long id){
        List<Subject>list=new ArrayList<>();
        String sql= "select * from s_subject where id=?";
        Connection con=DBUtil.getConnection();
        PreparedStatement ps=null;
        ResultSet rs=null;
        try {
            ps=con.prepareStatement(sql);
            ps.setLong(1,id);
            rs=ps.executeQuery();
            while (rs.next()){
                Subject subject=new Subject();
                subject.setId(rs.getInt("id"));
                subject.setGradeid(rs.getInt("gradeid"));
                subject.setSubjectname(rs.getString("subjectname"));
                subject.setClasshour(rs.getInt("classhour"));
                list.add(subject);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            DBUtil.close(con,ps,rs);
        }
        return list;
    }
    public List<Subject>find(int pageno,int pagesize){
        List<Subject>list=new ArrayList<>();
        Connection con=DBUtil.getConnection();
        PreparedStatement ps=null;
        ResultSet rs=null;
        String sql="select * from s_subject order by id limit ?,?";
        try {
            ps=con.prepareStatement(sql);
            ps.setInt(1,(pageno-1)*pagesize);
            ps.setInt(2,pagesize);
            rs=ps.executeQuery();
            while (rs.next()){
                Subject subject=new Subject();
                subject.setId(rs.getInt("id"));
                subject.setGradeid(rs.getInt("gradeid"));
                subject.setSubjectname(rs.getString("subjectname"));
                subject.setClasshour(rs.getInt("classhour"));
                list.add(subject);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return list;
    }
}
